#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import MySQLdb
import logging.config
from DBUtils.PooledDB import PooledDB
#from PooledDB import PooledDB
try:
    from common import Config_mod
except Exception as ex:
    print(ex)
    print('请将脚本放在项目根目录中运行')
    print('请检查项目根目录中的 common 文件夹是否存在')
    exit(-1)
logging.config.fileConfig("log/logging.ini")
logger = logging.getLogger("mysql")
log_error = logging.getLogger("error")
g_mysql_conf = {}

def Mysql_Config(**_mysql_conf):
    '''
    1.sys.path[0],当前目录路径
    2.os.path.split(os.path.realpath(__file__))[0] 得到的是当前文件模块的目录
    :return:
    '''
    global g_mysql_conf
    if not _mysql_conf:
        path = os.getcwd()+"/db.cnf"
        if os.path.isfile(path):
            g_mysql_conf['host'] = Config_mod.get_config(path,"mysqldb","host")
            g_mysql_conf['port'] = int(Config_mod.get_config(path,"mysqldb","port"))
            g_mysql_conf['user'] = Config_mod.get_config(path,"mysqldb","user")
            g_mysql_conf['passwd'] = Config_mod.get_config(path,"mysqldb","password")
            g_mysql_conf['db'] = Config_mod.get_config(path,"mysqldb","name")
            g_mysql_conf['charset'] = Config_mod.get_config(path,"mysqldb","charset")
            # if g_mysql_conf['name'] is "":
            #     g_mysql_conf['name'] = None
            return 1
        else:
            logger.warning("no find /db.cnf")
            return 0
    else:
        g_mysql_conf=_mysql_conf

class PTConnectionPool(object):
    __pool = None
    # def __init__(self):
    #     self.conn = self.__getConn();
    #     self.cursor = self.conn.cursor();
    def __enter__(self):
        self.conn = self.__getConn()
        self.cursor = self.conn.cursor()
        print u"PT数据库创建con和cursor"
        return self

    def __getConn(self):
        if self.__pool is None:
            self.__pool = PooledDB(creator=MySQLdb, mincached=1, maxcached=20,
                         **g_mysql_conf)
        return self.__pool.connection()


    #重连接池中取出一个连接
    def getconn(self):
        conn = self.__getConn()
        cursor = conn.cursor()
        return cursor,conn

    #关闭连接归还给连接池
    # def close(self):
    #     self.cursor.close()
    #     self.conn.close()
    #     print u"PT连接池释放con和cursor";


# def getPTConnection():
#     return PTConnectionPool()

class _MysqlPoolManager(object):
    """
    MYSQL数据库对象，负责产生数据库连接 , 此类中的连接采用连接池实现获取连接对象：conn = Mysql.getConn()
            释放连接对象;conn.close()或del conn
    """
    __pool = None
    def __init__(self):
        # 数据库构造函数，从连接池中取出连接，并生成操作游标
        self.conn = self.__getConn()
        self.cursor = self.conn.cursor()

    def __getConn(self):
        """
         @summary: 从连接池中取出连接
         @return MySQLdb.connection
         """
        if self.__pool is None:
            self.__pool = PooledDB(creator=MySQLdb, mincached=1, maxcached=20,
                         **g_mysql_conf)
        return self.__pool.connection()

    def getconn(self):
        return self.conn,self.cursor

    def __exit__(self, type, value, trace):
        '''
        @summary: 释放连接池资源
        :return:
        '''
        self.cursor.close()
        self.conn.close()
        print u"连接池释放con和cursor"

class dbConnet_Model(object):

    def __init__(self):
        self.cursor = None
        self.conn = None
        self._dbError = None
        self.isconnect = False
        try:
            _Mysql_pool = _MysqlPoolManager()
            self.conn,self.cursor = _Mysql_pool.getconn()
            self.isconnect = True
        except MySQLdb.Error ,e:
            try:
                self._dbError = "Error %d:%s" % (e.args[0], e.args[1])
            except IndexError:
                self._dbError = "MySQL Error:%s" % str(e)
            #print _dbError
            #log_error.exception(self._dbError)

    def get_conn(self):
        if self.isconnect :
            return self.conn
        else:
            return None

    def get_cursor(self):
        return self.cursor

    def close(self):
        if self.cursor:
            logger.debug(("%s close-start"% self.cursor))
            self.cursor.close()
            logger.debug("%s close-end"% self.cursor)
        if self.conn:
            logger.debug("%s close-start"% self.conn)
            self.conn.close()
            logger.debug("close-end")

    def conn_test(self):
        try:
            self.conn.ping()
        except :
            log_error.exception('this is an exception message')
        self.close()



if __name__ == '__main__':
    Mysql_Config()
    conn = dbConnet_Model()
    conn.close()
